import { compileToFunction } from "./compiler/index.js";
import { callHook, mountComponent } from "./lifecycle.js";
import { initState } from "./state";
import { mergeOptions } from "./utils/index.js";

export function initMixin(Vue) {
  Vue.prototype._init = function (options) {
    const vm = this;
    vm.$options = mergeOptions(vm.constructor.options, options);
    callHook(vm, "beforeCreate");
    initState(vm);
    callHook(vm, "created");
    if (options.el) {
      vm.$mount(options.el);
    }
  };

  Vue.prototype.$mount = function (el) {
    el = document.querySelector(el);
    const vm = this;
    if (!vm.$options.render) {
      let template;
      if (vm.$options.template) {
        template = vm.$options.template;
      } else {
        if (el) {
          template = el.outerHTML;
        }
      }
      if (template) {
        const render = compileToFunction(template);
        vm.$options.render = render;
      } else {
        throw new Error("template or render function not defined");
      }
    }
    mountComponent(vm, el);
  };
}
